package org.looop.studio.noots.document.handler;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.digester.Digester;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.looop.studio.noots.document.DocumentHandler;
import org.looop.studio.noots.document.DocumentHandlerException;
import org.xml.sax.SAXException;

public class DigesterXMLHandler implements DocumentHandler {

	private Digester dig;
	private static Document doc;
	public DigesterXMLHandler(){
		dig = new Digester();
		dig.setValidating(false);
		dig.addObjectCreate("address-book", DigesterXMLHandler.class);
		dig.addObjectCreate("address-book/contact", Contact.class);
		dig.addSetProperties("address-book/contact", "type", "type");
		dig.addCallMethod("address-book/contact/name", "setName", 0);
		dig.addCallMethod("address-book/contact/address", "setAddress", 0);
		dig.addCallMethod("address-book/contact/city", "setCity", 0);
		dig.addCallMethod("address-book/contact/province", "setProvince", 0);
		dig.addCallMethod("address-book/contact/postalcode", "setPostalcode", 0);
		dig.addCallMethod("address-book/contact/country", "setCountry", 0);
		dig.addCallMethod("address-book/contact/telephone", "setTelephone", 0);
		dig.addSetNext("address-book/contact", "populateDocument");
	}
	@Override
	public synchronized Document getDocument(InputStream is) throws DocumentHandlerException {
		try {
			dig.parse(is);
		} catch (IOException e) {
			throw new DocumentHandlerException(e);
		} catch (SAXException e) {
			throw new DocumentHandlerException(e);
		}
		return doc;
	}
	
	public void populateDocument(Contact contact){
		if(doc == null){
			doc = new Document();
		}
		doc.add(Field.Keyword("type", contact.getType()));
		doc.add(Field.Keyword("name", contact.getName()));
		doc.add(Field.Keyword("address", contact.getAddress()));
		doc.add(Field.Keyword("city", contact.getCity()));
		doc.add(Field.Keyword("province", contact.getProvince()));
		doc.add(Field.Keyword("postalcode", contact.getPostalcode()));
		doc.add(Field.Keyword("country", contact.getCountry()));
		doc.add(Field.Keyword("telephone", contact.getTelephone()));
	}
	
	public static void main(String[] args) throws Exception{
		DocumentHandler handler = new DigesterXMLHandler();
		InputStream in = new FileInputStream("contact.xml");
		Document doc = handler.getDocument(in);
		System.out.println(doc);
	}

}
